package cn.edu.hzvtc.service.impl;


import cn.edu.hzvtc.helper.StringHelper;
import cn.edu.hzvtc.mapper.UserMapper;
import cn.edu.hzvtc.model.entity.UserEntity;
import cn.edu.hzvtc.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void addUser(String username, String realname, String schoolId, String password, int userType) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(username);
        userEntity.setRealname(realname);
        userEntity.setStudentId(schoolId);
        userEntity.setUserType(userType);

        String pwdSalt = UUID.randomUUID().toString().replace("-", "");
        String pwd = StringHelper.generateMD5(password + pwdSalt);
        userEntity.setPwdSalt(pwdSalt);
        userEntity.setPwd(pwd);

        userEntity.setPwdValidDate(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000);
        userEntity.setPwdErrorCount(0);
        userEntity.setGradeId(0);
        userEntity.setClassId(0);

        System.out.println(userEntity);

        userMapper.addUser(userEntity);
    }

    @Override
    public boolean hasLogin(String username) {
      return redisTemplate.opsForValue().get("session_" + username) != null;
    }

    @Override
    public boolean login(String username, String password) {



        UserEntity userEntity = userMapper.findUserByUsername(username);

        System.out.println("userservice: user: "+userEntity);

        if (userEntity == null) {
            return false;
        }

        String pwdSalt = userEntity.getPwdSalt();
        String pwd = userEntity.getPwd();

        String inputPwd = StringHelper.generateMD5(password + pwdSalt);

        if (!pwd.equals(inputPwd)) {
            return false;
        }

        redisTemplate.opsForValue().set("session_"+username,userEntity.toString(),10, TimeUnit.MINUTES);

        return true;
    }
}
